package com.kamistoat.meimeichat.meimeichatserverapplication.netty.handlers;

import com.alibaba.fastjson.JSON;
import com.kamistoat.meimeichat.meimeichatserverapplication.entity.MmcUserEntity;
import com.kamistoat.meimeichat.meimeichatserverapplication.entity.MmcUserFriendEntity;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.NettyServerBizHandler;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.service.NettyUserService;
import com.kamistoat.meimeichat.meimeichatserverapplication.netty.utils.NettySocketChannelUtil;
import com.kamistoat.meimeichatserveraggrement.protocol.friend.AddFriendRequest;
import com.kamistoat.meimeichatserveraggrement.protocol.friend.AddFriendResponse;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * Netty处理添加好友请求的Handler
 */
@Component
/**
 * 如果使用与spring结合的Bean管理方式，需要为每一个Handler标注为Sharable。注意标注为多例模式不起作用。
 * 要么就是不要用Bean，每次都new新实例
 */
@ChannelHandler.Sharable
public class AddFriendHandlerServer extends NettyServerBizHandler<AddFriendRequest> {
    @Autowired
    NettyUserService nettyUserService;

    /**
     * Warning:子类只需要重写该方法
     *
     * Netty处理添加好友request
     */
    @Override
    public void channelRead(Channel channel, AddFriendRequest addFriendRequest) {
        if(addFriendRequest == null){
            return;
        }
        logger.info("添加好友请求处理: " + JSON.toJSONString(addFriendRequest));
        // 1. 将好友关系入库，双向入库 [A->B B->A]
        ArrayList<MmcUserFriendEntity> userFriendList = new ArrayList<>();
        userFriendList.add(new MmcUserFriendEntity(addFriendRequest.getUserId(), addFriendRequest.getFriendId()));
        userFriendList.add(new MmcUserFriendEntity(addFriendRequest.getFriendId(), addFriendRequest.getUserId()));
        nettyUserService.addUserFriend(userFriendList);

        // 2. 推送好友添加完成到A
        // 查询用户B详情
        MmcUserEntity cur_mmcUserEntity = nettyUserService.queryUserInfo(addFriendRequest.getFriendId());
        // 直接Flush出去
        channel.writeAndFlush(new AddFriendResponse(
                cur_mmcUserEntity.getUserId(), cur_mmcUserEntity.getUserNickname(), cur_mmcUserEntity.getUserHead()));

        // 3. 推送好友添加完成到B
        // 获取用户B的通道，从在线用户Map中获取用户B的通道
        Channel friend_channel = NettySocketChannelUtil.getChannel(addFriendRequest.getFriendId());
        // 只有B在线才进行推送
        if(friend_channel == null){
            return;
        }
        MmcUserEntity friend_mmcUserEntity = nettyUserService.queryUserInfo(addFriendRequest.getUserId());
        channel.writeAndFlush(new AddFriendResponse(
                friend_mmcUserEntity.getUserId(), friend_mmcUserEntity.getUserNickname(), friend_mmcUserEntity.getUserHead()));
    }
}
